package com.mc.read.adminapi.Aspect;

import com.mc.read.adminapi.manager.CacheManager;
import com.mc.read.dao.mapper.sys.SyslogMapper;
import com.mc.read.dao.mapper.sys.SyspermissionMapper;
import com.mc.read.dao.mapper.sys.SysuserMapper;
import com.mc.read.dao.models.sys.Syslog;
import com.mc.read.dao.models.sys.Sysuser;
import com.mc.read.vo.request.BaseRequest;
import com.mc.read.vo.respose.BaseRespose;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

/**
 * Created  by  fangjian on 2017/8/15
 */

@Component("mcMyAspect")
@Aspect
public class MyAspect {
    private static final Logger LOG = LoggerFactory.getLogger(MyAspect.class);
    @Autowired
    SyslogMapper syslogMapper;
    @Autowired
    SysuserMapper sysuserMapper;
    @Autowired
    SyspermissionMapper syspermissionMapper;
    @Autowired
    CacheManager cacheService;

    //日志
    @AfterReturning(value = "@annotation(userLog)", returning = "rvt")
    public void afterReturning(JoinPoint joinPoint, UserLog userLog, Object rvt) {
        try {
            Object[] args = joinPoint.getArgs();
            BaseRequest baseRequest = (BaseRequest) args[0];
            BaseRespose baseRespose = (BaseRespose) rvt;
            Sysuser sysuser = new Sysuser();
            //登录
            if (userLog.type() == 0) {
                if (baseRespose.getCode() == 200) {
                    sysuser = (Sysuser) baseRespose.getReturnString();
                } else {
                    return;
                }
            } else {
                try {
                    sysuser = cacheService.getSysUser(baseRequest.getUserId());
                } catch (Exception e) {
                    return;
                }
            }
            Syslog syslog = new Syslog();
            syslog.setOperatetime(new Date());
            syslog.setOperatetype(userLog.type());
            syslog.setPermissionname(userLog.operateName());
            syslog.setOperateuserid(sysuser.getUserid() + "");
            syslog.setOperateaccount(sysuser.getLoginname());
            syslog.setOperateusername(sysuser.getName());

            if (baseRespose.getCode() == 200) {
                syslog.setExecuteresult(1);
            } else {
                syslog.setExecuteresult(2);
            }
            syslog.setDescription(baseRespose.getDisp());
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            syslog.setIpaddress(getIpAddress(request));
            syslogMapper.insertSelective(syslog);
        } catch (Exception e) {
            LOG.error("日志记录失败{}", e);
        }
    }

    // 请求method前打印内容
    @Before(value = "@annotation(userPer)")
    public void methodBefore(JoinPoint joinPoint, UserPer userPer) throws Exception {
//    System.out.println("123");
        //        try {
//            Object[] args = joinPoint.getArgs();
//            BaseRequest baseRequest = (BaseRequest) args[0];
//            Sysuser sysuser = cacheService.getSysUser(baseRequest.getUserId());
//            if (sysuser.getUsertype() != 1) {
//                return;
//            }
//            Set<String> perSet = cacheService.getUserPer(baseRequest.getUserId());
//            if (!perSet.contains(userPer.permission())) {
//                throw new ServiceException(203020, "权限不足");
//            }
//            System.out.println(userPer.permission());
//        } catch (ServiceException e) {
//            throw new ServiceException(e.getcode(), e.getMessage());
//        } catch (Exception e) {
//            throw new ServiceException(203020, "权限验证失败");
//        }

    }



    /**
     * 获取客户端ip
     *
     * @param request
     * @return
     */
    public String getIpAddress(HttpServletRequest request) {


        /**
         proxy_set_header Host $host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         */
        String unknown = "unknown";

        String ipAddress = request.getHeader("x-remoter-ip");
        if (StringUtils.isEmpty(ipAddress) || unknown.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("x-forwarded-for");
        }
        if (StringUtils.isEmpty(ipAddress) || unknown.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ipAddress) || unknown.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ipAddress) || unknown.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();

            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡获取本机配置的IP地址
                InetAddress inetAddress = null;
                try {
                    inetAddress = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    LOG.error("UnknownHostException{}", e);
                }
                ipAddress = inetAddress.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实的IP地址，多个IP按照','分割
        if (null != ipAddress && ipAddress.length() > 15) {
            //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }

        return ipAddress;
    }
}
